<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item>
          <el-input
            v-model="listQuery.name"
            placeholder="请输入科目"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增科目</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :data="accountList"
        row-key="id"
        v-loading="listLoading"
        highlight-current-row
        border
        size="small"
        style="width: 100%"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="名称" sortable width="300px" prop="name">
          <template slot-scope="scope">
            <i
              :class="
                scope.row.children && scope.row.children.length > 0
                  ? 'el-icon-folder'
                  : 'el-icon-tickets'
              "
              style="color: #67c23a"
            />
            <span style="margin-left: 10px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="科目编码"
          prop="code"
          width="200px"
        ></el-table-column>
        <el-table-column
          align="center"
          label="说明"
          prop="desc"
          width="300px"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑科目' : '新增科目'"
      width="550px"
    >
      <el-form
        :model="accountForm"
        :rules="accountFormRules"
        ref="accountFormRef"
        label-width="100px"
        label-position="right"
        style="padding: 0 30px"
      >
        <el-form-item label="科目名称" prop="name">
          <el-input
            v-model="accountForm.name"
            placeholder="科目名称"
            maxlength="64"
            clearable
          />
        </el-form-item>
        <el-form-item label="科目编码" prop="code">
          <el-input
            v-model="accountForm.code"
            placeholder="科目编码(0101格式)"
            clearable
          />

        </el-form-item>
        <el-form-item label="父项">
          <el-cascader
            v-model="selectedKeys"
            :options="accountParentList"
            :props="props"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-form-item>

        <el-form-item label="说明">
          <el-input
            v-model="accountForm.desc"
            placeholder="科目说明"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveAccount">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAccountTitles,
  addAccountTitle,
  updateAccountTitle,
  delAccountTitle,
} from "@/api/base";
import { getParentsPath } from "@/utils/index";

const defaultForm = {
  id: undefined,
  name: "",
  code: null,
  desc: "",
  parent: undefined,
};

export default {
  name: "Account",
  data() {
    return {
      accountForm: Object.assign({}, defaultForm),

      accountFormRules: {
        name: [{ required: true, message: "请输入科目名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入科目编码", trigger: "blur" }],
      },

      dialogVisible: false,
      dialogType: "new",
      accountList: [],
      accountParentList: [],
      selectedKeys: [],
      codes: [],

      props: {
        expandTrigger: "hover",
        checkStrictly: true,
        value: "id",
        label: "name",
        children: "children",
      },

      listLoading: true,
      listQuery: {
        name: "",
      },
    };
  },

  created() {
    this.getAccounts();
    this.getParentAccounts();
  },

  methods: {


    getAccounts() {
      this.listLoading = true;
      getAccountTitles(this.listQuery)
        .then((res) => {
          this.accountList = res;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.listLoading = false;
        });
    },

    getParentAccounts() {
      getAccountTitles({}).then((res) => {
        this.accountParentList = res;
      });
    },

    // 查询
    handleFilter() {
      this.getAccounts();
    },

    // 增加权限
    handleAdd() {
      this.accountForm = Object.assign({}, defaultForm);
      this.getParentAccounts();
      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.accountFormRef.clearValidate();
      });
    },

    // 修改用户
    handleEdit(scope) {
      this.accountForm = Object.assign({}, scope.row);

      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(
          this.accountForm.parent,
          this.accountParentList
        );
        this.$refs["accountFormRef"].clearValidate();
      });
    },

    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该项吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delAccountTitle(row.id);
          this.getAccounts();
          this.getParentAccounts();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    // 保存操作
    async SaveAccount() {
      this.$refs.accountFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          console.log("OOOOO:", this.accountForm);
          const res = await updateAccountTitle(this.accountForm);
          console.log(isEdit, res);
          if (res) {
            this.getAccounts();
          }
        } else {
          const res = await addAccountTitle(this.accountForm);
          const { id } = res;
          if (id > 0) {
            this.getAccounts();
            this.getParentAccounts();
          }
        }

        const { name } = this.accountForm;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>科目名称: ${name}</div>
            `,
          type: "success",
        });
      });
    },

    handleChange(value) {
      console.log(this.selectedKeys);
      // 如果 selectedKeys 数组中的 length 大于0，证明选中的父级分类
      // 反之，就说明没有选中任何父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的Id
        this.accountForm.parent =
          this.selectedKeys[this.selectedKeys.length - 1];
      } else {
        // 父级分类的Id
        this.accountForm.parent = undefined;
      }
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  // .box-card{
  //   margin-top: 30px;
  // }
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .el-select,
  .el-cascader {
    width: 100%;
  }
}
</style>